import { request } from '../utils'
import realm from '../utils/realm'

export const writeLocal = params =>
  new Promise((resolve, reject) => {
    // 如果存在,加数量
    const obj = realm.objects('Cart').filtered(`id = "${params.id}"`)

    try {
      realm.write(() => {
        if (obj.length) {
          params.num += obj[0].num
          realm.create('Cart', params, true)
        } else {
          realm.create('Cart', params)
        }
        resolve()
      })
    } catch (e) {
      reject()
    }
  })

export const updateLocal = params =>
  new Promise((resolve, reject) => {
    try {
      realm.write(() => {
        realm.create('Cart', params, true)
      })
      resolve()
    } catch (e) {
      reject()
    }
  })

export const checkAllLocal = checked =>
  new Promise((resolve, reject) => {
    const data = realm.objects('Cart')
    try {
      realm.write(() => {
        data.map(item => {
          item.checked = checked
        })
      })
      resolve()
    } catch (e) {
      reject()
    }
  })
export const removeLocal = params =>
  new Promise((resolve, reject) => {
    const data = realm.objects('Cart')
    const obj = data.filtered(`id = "${params.id}"`)
    try {
      realm.write(() => {
        realm.delete(obj)
      })

      resolve()
    } catch (e) {
      reject()
    }
  })
export const clearLocal = params =>
  new Promise((resolve, reject) => {
    const data = realm.objects('Cart')

    try {
      realm.write(() => {
        realm.delete(data)
      })

      resolve()
    } catch (e) {
      reject()
    }
  })
export const queryLocal = () =>
  new Promise((resolve, reject) => {
    const data = realm.objects('Cart')
    resolve(data)
  })

export const view = params =>
  request({
    url: 'api/v1/shoppingCart/view',
    method: 'post',
    data: params,
    token: false,
  })
